{% extends "base.html" %}
{% block content %}
<div class="container mt-5">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card shadow">
                <div class="card-header bg-info text-white">
                    <h4 class="mb-0">群发邮件/短信</h4>
                </div>
                <div class="card-body">
                    <form id="emailForm" enctype="multipart/form-data">
                        <div class="form-group">
                            <label for="subject">邮件主题</label>
                            <input type="text" class="form-control" id="subject" name="subject">
                        </div>
                        <div class="form-group">
                            <label for="body">内容（邮件正文/短信内容）</label>
                            <div id="quill-toolbar"></div>
                            <div id="quill-editor" style="height: 200px;"></div>
                            <input type="hidden" id="body" name="body">
                        </div>
                        <div class="form-group">
                            <label for="excelFile">上传收件人Excel/CSV</label>
                            <input type="file" class="form-control-file" id="excelFile" name="file" accept=".xlsx,.xls,.csv" required>
                        </div>
                        <div class="form-group form-check">
                            <input type="checkbox" class="form-check-input" id="send_email" name="send_email" checked>
                            <label class="form-check-label" for="send_email">发送邮件</label>
                        </div>
                        <div class="form-group form-check">
                            <input type="checkbox" class="form-check-input" id="send_sms" name="send_sms">
                            <label class="form-check-label" for="send_sms">发送短信</label>
                        </div>
                        <button type="button" class="btn btn-primary btn-block" onclick="sendBatch()">发送</button>
                    </form>
                    <div id="result" class="mt-3"></div>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- Quill 富文本编辑器 -->
<link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
<script src="https://cdn.quilljs.com/1.3.6/quill.min.js"></script>
<script>
var toolbarOptions = [
    ['bold', 'italic', 'underline', 'strike'],
    ['blockquote', 'code-block'],
    [{ 'header': 1 }, { 'header': 2 }],
    [{ 'list': 'ordered'}, { 'list': 'bullet' }],
    [{ 'script': 'sub'}, { 'script': 'super' }],
    [{ 'indent': '-1'}, { 'indent': '+1' }],
    [{ 'direction': 'rtl' }],
    [{ 'size': ['small', false, 'large', 'huge'] }],
    [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
    [{ 'color': [] }, { 'background': [] }],
    [{ 'font': [] }],
    [{ 'align': [] }],
    ['link', 'image'],
    ['clean']
];
var quill = new Quill('#quill-editor', {
    modules: {
        toolbar: toolbarOptions
    },
    theme: 'snow',
    placeholder: '请输入邮件或短信内容...'
});
// 图片压缩处理
function compressImage(file, maxWidth = 800, quality = 0.7, callback) {
    const reader = new FileReader();
    reader.onload = function(event) {
        const img = new Image();
        img.onload = function() {
            const canvas = document.createElement('canvas');
            let width = img.width;
            let height = img.height;
            if (width > maxWidth) {
                height = height * (maxWidth / width);
                width = maxWidth;
            }
            canvas.width = width;
            canvas.height = height;
            const ctx = canvas.getContext('2d');
            ctx.drawImage(img, 0, 0, width, height);
            const dataUrl = canvas.toDataURL('image/jpeg', quality);
            callback(dataUrl);
        };
        img.src = event.target.result;
    };
    reader.readAsDataURL(file);
}
quill.getModule('toolbar').addHandler('image', function() {
    var input = document.createElement('input');
    input.setAttribute('type', 'file');
    input.setAttribute('accept', 'image/*');
    input.click();
    input.onchange = function() {
        var file = input.files[0];
        if (/^image\//.test(file.type)) {
            compressImage(file, 800, 0.7, function(dataUrl) {
                var range = quill.getSelection();
                quill.insertEmbed(range ? range.index : 0, 'image', dataUrl, 'user');
            });
        }
    };
});
function sendBatch() {
    const subject = document.getElementById('subject').value;
    // 获取富文本内容（HTML）
    const bodyHtml = quill.root.innerHTML;
    document.getElementById('body').value = bodyHtml;
    const excelFile = document.getElementById('excelFile').files[0];
    const sendEmail = document.getElementById('send_email').checked;
    const sendSms = document.getElementById('send_sms').checked;
    if ((!sendEmail && !sendSms) || !bodyHtml || !excelFile) {
        showResult('请填写内容、上传文件，并至少选择一种发送方式', 'danger');
        return;
    }
    const formData = new FormData();
    formData.append('subject', subject);
    formData.append('body', bodyHtml);
    formData.append('file', excelFile);
    if (sendEmail) formData.append('send_email', 'on');
    if (sendSms) formData.append('send_sms', 'on');
    fetch('/chat/send_messages_batch', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(res => {
        showResult(res.msg, res.code === 0 ? 'success' : 'danger');
    })
    .catch(err => {
        showResult('发送失败: ' + err, 'danger');
    });
}
function showResult(msg, type) {
    document.getElementById('result').innerHTML = `<div class="alert alert-${type}">${msg}</div>`;
}
</script>
{% endblock %}
